import { useHttp } from "hooks/useHttp";
import { useQuery } from "react-query";
import { Kanban, TaskType } from "types/kanban";
import { Task } from "types/epic";
import { useLocation } from "react-router";
import { useProject } from "views/project-list/util";
import { useMemo } from "react";
import { useUrlQueryParam } from "utils/url";
import { useDebounce } from "hooks/useDebounce";

export const useKanbans = (param?: Partial<Kanban>) => {
  const client = useHttp();
  return useQuery(["kanbans", param], () => client("kanbans", { data: param }));
};

export const useTasks = (param?: Partial<Task>) => {
  const client = useHttp();

  return useQuery(["tasks", param], () => client("tasks", { data: param }));
};

export const useTaskTypes = () => {
  const client = useHttp();

  return useQuery<TaskType[]>(["taskTypes"], () => client("taskTypes"));
};

export const useProjectIdInUrl = () => {
  const { pathname } = useLocation();
  const id = pathname.match(/projects\/(\d+)/)?.[1];
  return Number(id);
};

export const useProjectInUrl = () => useProject(useProjectIdInUrl());

export const useKanbanSearchParams = () => ({ projectId: useProjectIdInUrl() });

export const useKanbansQueryKey = () => ["kanbans", useKanbanSearchParams()];

export const useTasksSearchParams = () => {
  const projectId = useProjectIdInUrl();
  const [param] = useUrlQueryParam(["name", "typeId", "processorId", "tagId"]);
  const debouncedName = useDebounce(param.name, 200);

  return useMemo(
    () => ({
      projectId,
      name: debouncedName,
      typeId: Number(param.typeId) || undefined,
      processorId: Number(param.processorId) || undefined,
      tagId: Number(param.tagId) || undefined,
    }),
    [projectId, param, debouncedName]
  );
};

export const useTasksQueryKey = () => ["tasks", useTasksSearchParams()];
